package com.nlecloud.bc.util;

import org.apache.commons.io.FileUtils;

import javax.validation.constraints.Null;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author warrior
 * @description
 */
public class FileUtil {

    public static String searchFile(String dirPath, String fileName) {
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isFile() && file.getName().contains(fileName)) {
                return file.getName();
            }
        }
        return null;
    }

    /**
     * 访问url保存文件
     * @param accessUrl
     * @param filePath
     * @throws IOException
     */
    public static void saveFileFromUrl(String accessUrl,String filePath) throws IOException {
        URL url = new URL(accessUrl);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        FileUtils.copyURLToFile(url, file);
    }

    public static String getHtmlFromUrl(String accessUrl) throws IOException {
        URL url = new URL(accessUrl);
        URLConnection URLconnection = url.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
        InputStream in = httpConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader bufr = new BufferedReader(isr);
        String str;
        StringBuilder sb = new StringBuilder();
        while ((str = bufr.readLine()) != null) {
            sb.append(str);
        }
        bufr.close();
        return sb.toString();
    }

    public static void deleteFile(String filePath){
        File file = new File(filePath);
        file.delete();
    }

}
